import os.path
from typing import Final

from forward.config import get_settings
from forward.utils.config import ConfigUtil


class UrlUtil:
    domain: Final[str] = get_settings().domain
    upload_prefix: Final[str] = get_settings().upload_prefix
    static_prefix: Final[str] = get_settings().static_prefix

    @classmethod
    async def to_absolute_url(cls, url: str, engine="") -> str:
        """
        转绝对路径
        转前: /uploads/11.png 或 /static/11.png
        转后: https://127.0.0.1/uploads/11.png  或 https://127.0.0.1/static/11.png

        :param url: 相对路径
        :return:
        """
        if not url:
            return ""
        if url.find("/") != 0:
            url = "/" + url
        if url.startswith(cls.static_prefix):
            return cls.domain + get_settings().static_url + url.replace("/static/", "/")
        if not engine:
            engine = await ConfigUtil.get_val("storage", "default", "local")
        if engine == "local":
            return cls.domain + get_settings().upload_url + url
        config = await ConfigUtil.get_map("storage", engine)
        return config.get("domain") + url

    @classmethod
    async def to_relative_url(cls, url: str, engine=None) -> str:
        """
        转相对路径
        转前: https://127.0.0.1/uploads/11.png
        转后: /uploads/11.png
        :param url:
        :return:
        """
        if not url or not url.startswith("http"):
            return url
        if not engine:
            engine = await ConfigUtil.get_val("storage", "default", "local")
        if engine == "local":
            return url.replace(get_settings().domain, "").replace(
                os.path.join("/", cls.upload_prefix) + "/", "/"
            )
        config = await ConfigUtil.get_map("storage", engine)
        if config:
            return url.replace(config.get("domain", ""), "").replace(
                os.path.join("/", cls.upload_prefix) + "/", ""
            )
        return url
